var app = getApp();
const util = require('../../utils/util.js');
var QQMap = require('../../utils/qqmap-wx-jssdk.js');//腾讯地图服务
var map = new QQMap({
  key: 'HFTBZ-QFORG-CURQ3-IFONA-PRY2F-EGBXH'
});
var refresh = true;//手动刷新是否有效
Page({
  data: {
    refreshTip:false
  },
  onLoad: function (options) {
    let that = this;
    if(options.lat){
      that.getLoactionName(options.lat, options.lng,options.title);
      that.setData({
        lat: options.lat,
        lng: options.lng,
        title: options.title
      })
    }else{
      that.getLocation();
    }
    
  },
  getLocation:function(){
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        that.getLoactionName(latitude, longitude);
      },
      fail:function(res){
        wx.redirectTo({
          url: '../add/add',
        })
      }
    })
  },
  //逆地址解析(坐标位置描述)
  getLoactionName: function (latitude, longitude,title) {
    let that = this;
    that.realtime(latitude, longitude);
    that.forecast(latitude, longitude);
    map.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        that.setData({
          location: res.result
        })
        if(title){
          wx.setNavigationBarTitle({
            title: title,
          })
        }else{
          wx.setNavigationBarTitle({
            title: res.result.address_component.district,
          })
        }
        
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //实时天气
  realtime: function (latitude, longitude){
    let that= this;
    wx.request({
      method: 'GET',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      url: 'https://api.caiyunapp.com/v2/' + app.data.cy_token + '/' + longitude + ',' + latitude + '/realtime.json',
      success: function (res) {
        // 空气质量
        let aqi,aqiColor;
        if (res.data.result.aqi<=50){
          aqi = '优';
          aqiColor = '#6BCD07';
        } else if (res.data.result.aqi > 50 && res.data.result.aqi<=100){
          aqi = '良';
          aqiColor = '#FBD029';
        } else if (res.data.result.aqi > 100 && res.data.result.aqi <= 150) {
          aqi = '轻度污染';
          aqiColor = '#FE8800';
        } else if (res.data.result.aqi > 150 && res.data.result.aqi <= 200) {
          aqi = '中度污染';
          aqiColor = '#FE0000';
        } else if (res.data.result.aqi > 200 && res.data.result.aqi <= 300) {
          aqi = '重度污染';
          aqiColor = '#970454';
        } else if (res.data.result.aqi > 200 && res.data.result.aqi <= 300) {
          aqi = '严重污染';
          aqiColor = '#62001E';
        }
        res.data.result.pres = parseFloat(parseInt(res.data.result.pres)/1000).toFixed(2);
        res.data.result.temperature = parseInt(res.data.result.temperature);
        res.data.result.humidity = parseInt(res.data.result.humidity*100);
        console.log(res.data.server_time);
        that.setData({
          server_time: util.formatTime(res.data.server_time*1000),
          cloud: res.data.result,
          aqi:aqi,
          aqiColor:aqiColor
        })
      }
    })
  },
  // 天气预报
  forecast: function (latitude, longitude){
    let that = this;
    wx.request({
      method: 'GET',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      url: 'https://api.caiyunapp.com/v2/' + app.data.cy_token + '/' + longitude + ',' + latitude + '/forecast.jsonp',
      success: function (res) {
        let forecast = res.data.result;
        for (var value of forecast.daily.temperature) {
          value.date = value.date.slice(5,10);
          value.max = parseInt(value.max);
          value.min = parseInt(value.min);
        }
        //24小时预报
        for (var value of forecast.hourly.temperature) {
          value.datetime = value.datetime.slice(11, 16);
          value.value = parseInt(value.value);
        }
        // 5天预报
        for (var value of forecast.daily.aqi) {
          let aqi, aqiColor;
          if (value.max <= 50) {
            aqi = '优';
            aqiColor = '#6BCD07';
          } else if (value.max > 50 && value.max <= 100) {
            aqi = '良';
            aqiColor = '#FBD029';
          } else if (value.max > 100 && value.max <= 150) {
            aqi = '轻度污染';
            aqiColor = '#FE8800';
          } else if (value.max > 150 && value.max <= 200) {
            aqi = '中度污染';
            aqiColor = '#FE0000';
          } else if (value.max > 200 && value.max <= 300) {
            aqi = '重度污染';
            aqiColor = '#970454';
          } else if (value.max > 200 && value.max <= 300) {
            aqi = '严重污染';
            aqiColor = '#62001E';
          }
          value.aqi = aqi;
          value.apiColor = aqiColor;
        }
        that.setData({
          forecast:forecast
        })
        
      }
    })
  },
  // 重新定位
  refresh:function(){
    if (refresh) {
      refresh = false;
      this.getLocation();
      const time = setTimeout(() => {
        refresh = true;
        that.setData({
          refreshTip: true
        })
      }, 60 * 1000)
    }else{
      wx.showToast({
        title: '刷新太快了',
        icon: 'none'
      })
    }
  },
  // 添加地址
  add:function(){
    wx.navigateTo({
      url: '../add/add',
    })
  },
  // 关于我
  about:function(){
    wx.navigateTo({
      url: '../about/about',
    })
  },
  //下拉刷新天气
  onPullDownRefresh: function () {
    let that = this;
    // 手动刷新 有效刷新
    if (refresh){
      refresh = false;
      //如果为搜索的地址，则刷新不重新请求定位
      if (that.data.lat && that.data.lng && that.data.title){
        that.getLoactionName(that.data.lat, that.data.lng, that.data.title);
      }else{
        this.getLocation();
      }
      const time = setTimeout(() => {
        refresh = true;
        that.setData({
          refreshTip: true
        })
      }, 60 * 1000)
    }else{
      wx.showToast({
        title: '刷新太快了',
        icon:'none'
      })
    }
    wx.stopPullDownRefresh();
  },
  onShareAppMessage:function(){
    let that = this;
    let title = '这可能是东半球最好用的天气小程序';
    let sky = that.data.cloud.skycon;
    if (sky =='CLEAR_DAY'){
      title = '阳光美美哒~';
    } else if (sky == 'CLEAR_NIGHT'){
      title = '漫漫长夜，月色撩人哪~';
    } else if (sky == 'CLOUDY') {
      title = '天空灰的像哭过~';
    } else if (sky == 'RAIN') {
      title = '雨一直下，气氛不算融洽~';
    } else if (sky == 'SNOW') {
      title = '最浪漫的事就是和你一起白头~';
    } else if (sky == 'WIND') {
      title = '风吹乱我的秀发，连他也嫉妒我的俊美！';
    } else if (sky == 'HAZE') {
      title = '讲真的，这个天还是待在屋里吧！';
    } else if (sky == 'FOG') {
      title = '世界上最远的就是我站在你面前，而你缺看不见~';
    } else if (sky == 'SLEET') {
      title = '冻雨天气，请注意安全！';
    }
    return {
      title: title,
      path: '/pages/index/index',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  }
})
